package com.yupi.yuojbackendquestionservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.yuojbackendcommon.common.ErrorCode;
import com.yupi.yuojbackendcommon.constant.CommonConstant;
import com.yupi.yuojbackendcommon.exception.BusinessException;
import com.yupi.yuojbackendcommon.utils.SqlUtils;
import com.yupi.yuojbackendquestionservice.mapper.QuestionSubmitMapper;
import com.yupi.yuojbackendquestionservice.rabbitmq.MyMessageProducer;
import com.yupi.yuojbackendquestionservice.service.QuestionService;
import com.yupi.yuojbackendquestionservice.service.QuestionSubmitService;
import com.yupi.yuojbackendserviceclient.service.JudgeFeignClient;
import com.yupi.yuojbackendserviceclient.service.UserFeignClient;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import yuojbackendmodel.model.dto.questionsubmit.QuestionSubmitAddRequest;
import yuojbackendmodel.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import yuojbackendmodel.model.entity.Question;
import yuojbackendmodel.model.entity.QuestionSubmit;
import yuojbackendmodel.model.entity.User;
import yuojbackendmodel.model.enums.QuestionSubmitLanguageEnum;
import yuojbackendmodel.model.enums.QuestionSubmitStausEnum;
import yuojbackendmodel.model.vo.QuestionSubmitVO;
import yuojbackendmodel.model.vo.QuestionVO;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @author JFeng
 * @description 针对表【question_submit(提交题目)】的数据库操作Service实现
 * @createDate 2023-09-20 22:10:13
 */
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
        implements QuestionSubmitService {
    @Resource
    private QuestionService questionService;

    @Resource
    private UserFeignClient userFeignClient;

    @Resource
    @Lazy
    private JudgeFeignClient judgeFeignClient;

    @Resource
    private QuestionSubmitMapper questionSubmitMapper;

    @Resource
    private MyMessageProducer myMessageProducer;

    /**
     * 提交题目
     *
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {

        String language = questionSubmitAddRequest.getLanguage();
        QuestionSubmitLanguageEnum enumByValue = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if (enumByValue == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言错误");
        }
        // 判断实体是否存在，根据类别获取实体
        Long questionId = questionSubmitAddRequest.getQuestionId();
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 是否已提交题目
        long userId = loginUser.getId();
        // 每个用户串行提交题目
        // 锁必须要包裹住事务方法
//        QuestionSubmitService questionSubmitService = (QuestionSubmitService) AopContext.currentProxy();
//        synchronized (String.valueOf(userId).intern()) {
//            return questionSubmitService.doQuestionSubmitInner(userId, questionId);
//        }
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        questionSubmit.setLanguage(language);
        questionSubmit.setStatus(QuestionSubmitStausEnum.WAITING.getValue());
        questionSubmit.setJudgeInfo("{}");
        questionSubmit.setCreateTime(new Date());
        boolean save = this.save(questionSubmit);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据处理异常");
        }
        Long questionSubmitId = questionSubmit.getId();
        // 执行判题服务
        myMessageProducer.sendMessage("code_exchange", "my_routingKey", String.valueOf(questionSubmitId));
//        CompletableFuture.runAsync(() -> {
//            judgeFeignClient.doJudge(questionSubmitId);
//        });
        return questionSubmitId;
    }

    /**
     * 获取查询包装类
     * 用户可能根据哪些
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.eq(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(QuestionSubmitStausEnum.getEnumByValue(status) != null, "status", status);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }


    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);

        //脱敏  仅本人和管理员能看见自己提交的代码的答案
        Long userId = loginUser.getId();
        if (!Objects.equals(userId, questionSubmit.getUserId()) && !userFeignClient.isAdmin(loginUser)) {
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
    }

    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollectionUtils.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        List<QuestionSubmit> records = questionSubmitPage.getRecords();
        // 关联查用户信息
        Set<Long> userIdSet = records.stream().map(QuestionSubmit::getUserId).collect(Collectors.toSet());
        List<User> userList = userFeignClient.listByIds(userIdSet);
        // 填充信息
        List<QuestionSubmitVO> questionSubmitVOList = records.stream().map(s -> {
            QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(s);
            for (User user : userList) {
                if (Objects.equals(user.getId(), s.getUserId())) {
                    questionSubmitVO.setUserAccount(user.getUserAccount());
                }
            }
            return questionSubmitVO;
        }).collect(Collectors.toList());

        // 关联查询题目
        Set<Long> qusetionIdSet = records.stream().map(QuestionSubmit::getQuestionId).collect(Collectors.toSet());
        List<Question> questionList = questionService.listByIds(qusetionIdSet);
        // 填充题目信息
        questionSubmitVOList.forEach(s -> {
            for (Question question : questionList) {
                if (Objects.equals(question.getId(), s.getQuestionId())) {
                    QuestionVO questionVO = QuestionVO.objToVo(question);
                    s.setQuestionVO(questionVO);
                }
            }
        });

        questionSubmitVOPage.setRecords(questionSubmitVOList);
//        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream().map(questionSubmit ->
//                getQuestionSubmitVO(questionSubmit, loginUser)
//        ).collect(Collectors.toList());
//        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }

    @Override
    public Page<QuestionSubmitVO> selectByCondition(Page<QuestionSubmitVO> page, QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        String language = questionSubmitQueryRequest.getLanguage();
        String title = questionSubmitQueryRequest.getTitle();
        String userAccount = questionSubmitQueryRequest.getUserAccount();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();
        Page<QuestionSubmitVO> questionSubmitVOList = questionSubmitMapper.selectByCondition(page, language, title, userAccount, sortField, sortOrder);
//        questionSubmitVOList.getRecords().forEach(q->{
//            JudgeInfo judgeInfo = JSONUtil.toBean(q.getJudgeInfoStr(), JudgeInfo.class);
//            q.setJudgeInfo(judgeInfo);
//        });

        return questionSubmitVOList;
    }

}




